<?php

namespace App\Http\Controllers;

use App\Http\Requests\TopicsForm;
use App\Models\Category;
use App\Models\Communities;
use App\Models\District;
use App\Models\Topics;
use Barryvdh\Debugbar\Twig\Extension\Dump;
use Carbon\Carbon;
use function gl\user_is_disabled;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TopicsController extends Controller
{

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $order   = $request->input('order');
        $builder = Topics::query()->order($order)->with(['category:name,id', 'community', 'user']);
        if (isset($request->category)) {
            $builder->where('category_id', $request->category);
            $category = Category::query()->where('id', $request->category)->first();
        }
        $params = [
            'category_name' => $category->name ?? '全部信息',
            'category_id'   => $category->id ?? null,
            'order'         => $order,
        ];
        if (isset($request->global_city)) {
            $builder->where('city_id', $request->global_city->id);
            $params['county_info'] = $request->global_city->children;
        }
        if (isset($request->global_city)) {
            $params['city']   = $request->global_city;
            $city_id          = $request->global_city->id;
            $params['county'] = $request->input('county');
            if (isset($params['county'])) {
                $county = District::query()
                    ->where([['parentid', $city_id], ['name', $request->input('county')]])->first();
                if (in_array($request->global_city->id, [1, 2, 3, 4])) {
                    $communities = Communities::query()->where('city_id', $county->id)->get();
                } else {
                    $communities = Communities::query()->where('county_id', $county->id)->get();
                }
                $builder->where('county_id', $county->id);
                $params['communities'] = $communities;
                $community_name        = $request->input('community');
                if (isset($community_name)) {
                    if (in_array($request->global_city->id, [1, 2, 3, 4])) {
                        $community = Communities::query()->where([['province_id', $city_id], ['city_id', $county->id], ['name', $community_name]])->first();
                    } else {
                        $community = Communities::query()->where([['city_id', $city_id], ['county_id', $county->id], ['name', $community_name]])->first();
                    }
                    $builder->where('community_id', $community->id);
                    $params['community_name'] = $community_name;
                }
            }
        }
        $info           = $builder->orderBy('created_at', 'desc')->paginate(config('custom.page'));
        $params['info'] = $info;

        return view('topics.index', $params);
    }

    public function show(Category $category, Topics $topics)
    {
        $topics->timestamps = false;
        $topics->view_count = $topics->view_count + 1;
        $topics->save();

        return view('topics.show', [
            'topic' => $topics,
            'id'    => $topics->id,
        ]);
    }

    public function getTopicjson(Topics $topics)
    {
        $user     = Auth::user();
        $response = [
            'id'                => $topics->id,
            'title'             => $topics->title,
            'body'              => $topics->body,
            'created_at'        => Carbon::createFromTimeString($topics->created_at)->diffForHumans(),
            'user_name'         => $topics->user->name,
            'user_id'           => $topics->user->id,
            'user_created_at'   => Carbon::createFromTimeString($topics->user->created_at)->diffForHumans(),
            'user_introduction' => $topics->user->introduction,
            'reply_count'       => $topics->reply_count,
            'view_count'        => $topics->view_count,
            'auth'              => Auth::check(),
        ];
        if (Auth::check()) {
            $response['can_delete'] = $user->can('delete', $topics);
            $response['can_update'] = $user->can('update', $topics);
        }
        if (!@fopen($topics->user->avatar)) {
            $response['user_avatar'] = '/img/avatar.png';
        } else {
            $response['user_avatar'] = $topics->user->avatar;
        }
        return response()->json($response);
    }

    public function form(Request $request)
    {
        $user = Auth::user();
        if ($user->created_at->diffInSeconds() < config('custom.publish_time_limit')) {
            return view('topics.msg',['msg' => config('custom.not_publish_msg')]);
        }
        if(user_is_disabled($user)) {
            return view('topics.msg',['msg' => "您的账号被禁用{$user->disabled_duration}天，请{$user->disabled_duration}天以后再来发布信息"]);
        }
        if (!isset($request->global_city)) {
            return redirect()->route('cities');
        }
        $id    = $request->id;
        $topic = null;
        if ($request->has('cat_id')) {
            $params['category_id'] = $request->input('cat_id');
        }
        if (isset($id)) {
            $topic = Topics::where('id', $id)->first();
        }
        $params['id']    = $id;
        $params['topic'] = $topic;
        if (isset($request->global_city)) {
            $params['city_id'] = $request->global_city->id;
        }
        $params['county_info'] = $request->global_city->children;
        return view('topics.form', $params);
    }

    public function save(TopicsForm $request)
    {
        $user = Auth::user();
        if ($user->created_at->diffInSeconds() < config('custom.publish_time_limit')) {
            abort(422,config('custom.not_publish_msg'));
        }
        if(user_is_disabled($user)) {
            abort(422,"您的账号被禁用{$user->disabled_duration}天，请{$user->disabled_duration}天以后再来发布信息");
        }
        $id          = $request->input('id');
        $category_id = $request->input('category_id');
        if (isset($id)) {
            $this->authorize('update', Topics::find($id));
            $res = Topics::where('id', $id)->update($request->except('_token'));
        } else {
            $data            = $request->except('_token');
            $data['user_id'] = Auth::user()->id;
            $res             = Topics::create($data);
            $id              = $res->id;

        }
        if ($res) {
            return response()->json(['status' => true, 'cat_id' => $category_id, 'id' => $id]);
//            return redirect()->route('topics.show', [$category_id, $id]);
        }
    }

    public function delete(Request $request)
    {
        $id = $request->input('id');
        $this->authorize('delete', Topics::find($id));
        $res = Topics::destroy($id);
        return response()->json(['status' => $res]);
    }

    public function setTop(Request $request)
    {
        $id    = $request->id;
        $topic = Topics::find($id);
        $this->authorize('setTop', Topics::find($id));
        if ($topic->order == -1) {
            Topics::query()->where('id', $id)->update(['order' => 0]);
        } else {
            Topics::query()->where('id', $id)->update(['order' => -1]);
        }
        return back();
    }
}
